<?php
namespace App\Http\Controllers;

use App\Http\Resources\PermissionResource;
use App\Http\Resources\RoleResource;
use App\Http\Resources\UserResource;
use App\Models\Permission;
use App\Models\Role;
use App\Models\User;
use App\Traits\ResponseTrait;
use Illuminate\Http\Request;

class AuthController extends Controller
{
    use ResponseTrait;

    /**
     * Get a JWT token via given credentials.
     *
     * @param \Illuminate\Http\Request $request
     *
     * @return \Illuminate\Http\JsonResponse
     * @throws \Illuminate\Validation\ValidationException
     */
    public function login(Request $request)
    {
        // 验证规则，由于业务需求，这里我更改了一下登录的用户名，使用手机号码登录
        $rules = [
            'username'   => [
                'required',
                'exists:users',
            ],
            'password' => 'required|string|min:6|max:20',
        ];

        // 验证参数，如果验证失败，则会抛出 ValidationException 的异常
        $params = $this->validate($request, $rules);
        // 使用 Auth 登录用户，如果登录成功，则返回 201 的 code 和 token，如果登录失败则返回
        $token = auth('api')->attempt($params);
        if ($token) {
//            $user = auth('api')->user();
//            $user->permissions = $user->getAllPermissions();
//            $user->token = 'Bearer ' . $token;
//            return $this->success('登陆成功', new UserResource($user));
            return $this->success('登陆成功', ['token' => 'Bearer ' . $token]);
        } else {
            return $this->failure('账号或密码错误');
        }
    }

    public function profile()
    {
        $user = auth('api')->user();
        $user->load('permissions');
        return $this->success('获取用户信息成功', UserResource::make($user));
    }

    /**
     * 处理用户登出逻辑
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function logout()
    {
        auth('api')->logout();

        return $this->success('退出成功');
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * 数据表格接口
     */
    public function data(Request $request)
    {
        $model = $request->get('model');
        switch (strtolower($model)) {
            case 'role':
                $rows = Role::all(['id', 'display_name'])->sortByDesc('updated_at');
                break;
            case 'permission':
                $rows = Permission::all(['id', 'display_name', 'parent_id'])->sortByDesc('sort');
                break;
            case 'user':
            default:
                $rows = User::all(['id', 'display_name'])->sortByDesc('updated_at');
                break;
        }
        return $this->success('get data success', $rows);
    }
}
